package control;

import com.alibaba.fastjson.JSON;
import entity.User;
import utils.XHHashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class BaseServlet extends HttpServlet {
    //直接定义loginUser，方便取用
    public User loginUser;

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        loginUser = (User) request.getSession().getAttribute("loginUser");

        //获取请求的URI  http://localhost:8080/user/login --> /user/login
        String uri = request.getRequestURI();

        // 从最后一个`/`开始截取 /user/login ---> login
        uri = uri.substring(uri.lastIndexOf("/") + 1);

        // 具体的servlet
        Class targetClass = this.getClass();

        try {
            // 通过截取uri(方法名),反射出对应的方法
            Method method = targetClass.getDeclaredMethod(uri, HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(true);

            // 传入参数并执行方法
            method.invoke(this, request, response);

        }catch (InvocationTargetException e) {
            Throwable realException = e.getCause();
            realException.printStackTrace();
            // 或根据实际场景处理，比如记录日志、返回错误信息给前端等
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取request中的键值对，返回Map<String,String>
     *
     * @return
     */
    public static Map<String, String> getParam(HttpServletRequest request) {

        Map<String, String> returnMap = new XHHashMap();

        // request中封装的前端的值
        Map<String,String[]> parameterMap = request.getParameterMap();

        for (String key : parameterMap.keySet()) {

            String[] values = parameterMap.get(key);
            // 真的提交了多值(多选框)
            if (values.length > 1) {

                // 使用逗号拼接字符串 [3,4,5,6,7]
                String val = Arrays.toString(values);

                returnMap.put(key, val);
            } else {
                //只要第0个下标的值
                returnMap.put(key, values[0]);
            }
        }

        return returnMap;
    }
    /**
     * 将数据以json方式写到前端
     * @param response
     * @param object
     * @return
     */
    public void writerObjToString(HttpServletResponse response,Object object) {
        try {
            String jsonStr = JSON.toJSONString(object);

            response.setContentType("application/json;charset=utf8");

            response.getWriter().write(jsonStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
